package main

import (
	"os"
	"fmt"
	"io/ioutil"
	"strconv"
	"io"
)

/*
作业3：断点续传
 */
var srcPath string = "/home/daniel/tmp/萌猫.jpg"
var destPath string = "/home/daniel/tmp/萌猫4.jpg"

func main()  {
	copy(srcPath, destPath)
}

func copy(srcPath, destPath string)  {

	//获取临时记录
	//var count int
	countPath := destPath+"_count"
	data1,_ := ioutil.ReadFile(countPath)
	count1 ,err := strconv.Atoi(string(data1))

	//源文件，目标文件
	srcFile,_ := os.Open(srcPath)
	destFile,_ := os.OpenFile(destPath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	destInfo,_ := destFile.Stat()

	defer func() {
		srcFile.Close()
		destFile.Close()
		msg := recover()
		fmt.Println("err:", msg)
	}()

	var count int64 = int64(count1)
	if isDown(destPath, srcPath) {
		count = destInfo.Size()
	}

	if err != nil {
		fmt.Println("未传过")
		count1 = 0
	}

	//续传位置
	destFile.Seek(count,0) //同样的位置, 上次停下的位置
	srcFile.Seek(count, 0) //

	//读取数据
	bs := make([]byte,1024,1024)

	for {
		n,err := srcFile.Read(bs)


		//复制完成， 删除临时记录文件
		if n == 0 || err == io.EOF {
			fmt.Println("复制结束")
			os.Remove(countPath)
			break
		}

		//复制写出
		destFile.Write(bs[:n])

		//更新size，更新记录
		count += int64(n)
		strSize := strconv.Itoa(int(count))
		ioutil.WriteFile(countPath, []byte(strSize), os.ModePerm)

		brokeDown(count)
	}

	fmt.Println(count)

}

func isDown(fstr1, fstr2 string) bool {

	finfo1,_ := os.Stat(fstr1)
	finfo2,_ := os.Stat(fstr2)

	return  finfo1.Size() == finfo2.Size()
}

func brokeDown(size int64)  {
	if size >= 1024*10 && size <= 1024*11 {
		panic("网络挂掉了")
	}
}

/**
获取文件大小
 */
func getFileSize(path string) int {
	info,_ :=os.Stat(path)
	return int(info.Size())
}
